package com.company.cloud.user.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.user.modules.api.constant.UserOneSourceEnum;
import com.company.cloud.user.modules.api.constant.UserRegisterWayEnum;
import com.company.cloud.user.modules.api.models.UserModel;
import com.company.cloud.user.modules.api.request.UserMgrUpdateParam;
import com.company.cloud.user.modules.api.request.UserPtQuery4PageParam;
import com.company.cloud.user.modules.api.request.UserRegisterParam;
import com.company.cloud.user.modules.api.response.UserInfoQueryResp;
import com.company.cloud.user.modules.api.service.UserPlatformRemoteService;
import com.company.cloud.user.modules.app.service.UserRegisterService;
import com.company.cloud.user.modules.base.entity.DeptInfo;
import com.company.cloud.user.modules.base.entity.UserInfo;
import com.company.cloud.user.modules.base.entity.UserRoleInfo;
import com.company.cloud.user.modules.base.service.DeptInfoService;
import com.company.cloud.user.modules.base.service.UserInfoService;
import com.company.cloud.user.modules.base.service.UserRoleInfoService;
import com.company.cloud.user.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.user.modules.cache.utils.UserConvertUtils;
import com.company.cloud.user.modules.mgr.service.UserMgrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@Service
public class UserPlatformRemoteServiceImpl implements UserPlatformRemoteService {

    @Autowired
    private UserRegisterService userRegisterService;

    @Autowired
    private UserMgrService userMgrService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private UserRoleInfoService userRoleInfoService;
    @Autowired
    private UserPermissionCacheService userPermissionCacheService;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public BaseClientResult<String> saveUser(UserRegisterParam params) {
        params.setSourceOne(UserOneSourceEnum.Admin_Reg.getCode());
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        params.setCompanyNo(userInfo.getCompanyNo());
        this._registerByUserName2Mobile(params);
        return BaseClientResult.ok();
    }

    @Override
    public BaseClientResult<String> updateUser(UserMgrUpdateParam params) {
        ValidatorUtils.validate(params);
        userMgrService.update(params, new LoginSimpleUserInfo("admin|PT"));
        userPermissionCacheService.logoutUser(new LoginSimpleUserInfo(Integer.toString(params.getId())));
        return BaseClientResult.ok();
    }

    @Override
    public BaseClientResult<List<UserModel>> queryUsers(UserPtQuery4PageParam params) {
        List<UserInfo> list = userInfoService.list(new QueryWrapper<UserInfo>()
                .eq(StringUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
                .eq(StringUtils.hasText(params.getUserType()), "user_type_one", params.getUserType())
                .eq(StringUtils.hasText(params.getUserState()), "user_state", params.getUserState())
                .like(StringUtils.hasText(params.getUserName()), "user_name", params.getUserName())
                .like(StringUtils.hasText(params.getNickName()), "nick_name", params.getNickName())
                .likeRight(StringUtils.hasText(params.getMobile()), "mobile", params.getMobile())
        );
        if (CollectionUtils.isEmpty(list)) {
            return BaseClientResult.error(BaseReturnEnum.DATA_NOT_EXISTS.getCode(), BaseReturnEnum.DATA_NOT_EXISTS.getMsg());
        }
        List<UserModel> result =
                list.stream().map(UserConvertUtils::getUserModel).collect(Collectors.toList());
        return BaseClientResult.ok(result);
    }

    /**
     * 用户列表查询
     *
     * @param params
     */
    @Override
    public BaseClientResult<UserInfoQueryResp> queryUser(UserPtQuery4PageParam params) {
        IPage<UserInfo> page = userInfoService.page(
                new Page<UserInfo>(params.getPage(), params.getRows()), new QueryWrapper<UserInfo>()
                        .eq("company_no", params.getCompanyNo())
                        .eq(StringUtils.hasText(params.getUserType()), "user_type_one", params.getUserType())
                        .eq(StringUtils.hasText(params.getUserState()), "user_state", params.getUserState())
                        .like(StringUtils.hasText(params.getUserName()), "user_name", params.getUserName())
                        .like(StringUtils.hasText(params.getNickName()), "nick_name", params.getNickName())
                        .likeRight(StringUtils.hasText(params.getMobile()), "mobile", params.getMobile())
                        .orderByDesc("reg_time")
        );

        final String[] deptName = {""};
        Set<Integer> deptIds = new HashSet<Integer>();
        if (page != null && !CollectionUtils.isEmpty(page.getRecords())) {
            for (UserInfo item : page.getRecords()) {
                List<UserRoleInfo> userRoleList = userRoleInfoService.list(
                        new QueryWrapper<UserRoleInfo>().eq("user_id", item.getId())
                );
                userRoleList.forEach(m -> {
                    deptIds.add(m.getId());
                    DeptInfo deptInfo = deptInfoService.getBaseMapper().selectOne(new QueryWrapper<DeptInfo>().
                            eq("id", m.getId())
                    );
                    if (deptInfo != null) {
                        deptName[0] = deptInfo.getName();
                    }
                });


            }
        }

        //Map<Integer, DeptInfo> deptMap = userRoleDeptTeamCacheService.getDeptMap(deptIds);
        String finalDeptName = deptName[0];
        IPage<UserModel> data = page.convert(new Function<UserInfo, UserModel>() {
            @Override
            public UserModel apply(UserInfo entity) {
                UserModel model = UserConvertUtils.getUserModel(entity);
                System.out.println("=============" + finalDeptName + "======================");
                model.setDeptName(finalDeptName);
                return UserConvertUtils.getUserModel(entity);

            }
        });

        UserInfoQueryResp resp = new UserInfoQueryResp();
        resp.setRecords(data.getRecords());
        resp.setTotal(data.getTotal());
        resp.setPages(data.getPages());
        resp.setSize(data.getSize());
        resp.setCurrent(data.getCurrent());

        return BaseClientResult.ok(resp);
    }

    @Override
    public BaseClientResult<UserModel> getUser(Integer id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo == null) {
            return BaseClientResult.error(BaseReturnEnum.DATA_NOT_EXISTS.getCode(), BaseReturnEnum.DATA_NOT_EXISTS.getMsg());
        }
        return BaseClientResult.ok(UserConvertUtils.getUserModel(userInfo));
    }

    /**
     * 手机注册
     */
    private UserInfo _registerByUserName2Mobile(UserRegisterParam params) {
        ValidatorUtils.validate(params);
        params.setRegIp(HttpContextUtils.getClientIP());
        params.setRegWay(UserRegisterWayEnum.Reg_Mobile_UserName.getCode());
        UserInfo user = userRegisterService.register(params, null);
        return user;
    }

}
